package com.chookss.video.recommend

import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ExpandableListView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModelProviders
import com.chookss.MyApp
import com.chookss.R
import com.chookss.base.StaticClass
import com.chookss.tools.MyEvent
import com.chookss.tools.Utils
import com.chookss.tools.httpForm
import com.chookss.video.VideoCommentsAdapter
import com.chookss.video.VideoCommentsInputDialog
import com.chookss.video.entity.VideoComment
import com.chookss.video.entity.VideoEntity
import com.chookss.video.model.VideoModel
import com.chookss.video.response.VideoCommentsListResponse
import com.johnrambo.ktea.ktExtends.ShareUtils
import errorToast
import kotlinx.android.synthetic.main.item_load_more.view.*
import org.greenrobot.eventbus.EventBus
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2021/1/26 18:04
 * Note:
 */
class VideoDetailCommentFragment() : Fragment() {
    var listView: ExpandableListView? = null
    var video: VideoEntity? = null
    var context: Activity? = null
    var footerView: View? = null
    var adapter: VideoCommentsAdapter? = null
    var pageSize = 20
    var isLoading = false
    var isFirst = false
    var isEnd = false

    var viewModel:VideoModel? = null

    fun VideoDetailCommentFragment() {
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = activity
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_video_detail_comments, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        video = getArguments()?.getSerializable("video") as VideoEntity?
        footerView=LayoutInflater.from(context).inflate(R.layout.item_load_more, null)
        listView = view.findViewById(R.id.listView)
        listView?.addFooterView(footerView, null, false)
        adapter= object : VideoCommentsAdapter() {
            override fun getGroupView(
                groupPosition: Int,
                isExpanded: Boolean,
                convertView: View?,
                parent: ViewGroup
            ): View {
                if (groupPosition == groupCount - 1) {
                    loadMoreData()
                }
                return super.getGroupView(groupPosition, isExpanded, convertView, parent)
            }
        }
        listView?.setAdapter(adapter)
        listView?.setGroupIndicator(null)
        listView?.setOnGroupClickListener { parent, v, groupPosition, id ->
            adapter?.getGroup(groupPosition)?.let { showReplyCommentDialog(it, null) }
            true
        }
        listView?.setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
            if (adapter?.getChildType(
                    groupPosition,
                    childPosition
                ) == VideoCommentsAdapter.ChildTypePlaceHolder
            ) {
                clickOnChildPlaceholder(groupPosition)
            } else {
                var groupItem = adapter?.getGroup(groupPosition)
                groupItem?.let { showReplyCommentDialog(it, groupItem.children[childPosition]) }
            }
            true
        }
        loadMoreData()
        adapter?.onItemBtnClick = object : VideoCommentsAdapter.OnItemBtnClick {
            override fun onCommentClick(view: View, comment: VideoComment) {
                likeComment(view, comment)
            }
        }
        viewModel = ViewModelProviders.of(context as FragmentActivity).get(VideoModel::class.java)
    }
    fun changeData( newVideo: VideoEntity){
         video=newVideo
         isLoading = false
         isFirst = false
         isEnd = false
        adapter?.groups?.clear()
        adapter?.notifyDataSetChanged()
        loadMoreData()
    }
    private fun likeComment(v: View, entity: VideoComment) {
        var isLike = !v.isSelected
        viewModel?.likeComment(entity.commentCode, entity.videoComment, isLike, {
            var numInt: Int = 0
            if (!Utils.isNull(entity.commentLikeCounts)) {
                numInt = entity.commentLikeCounts.toInt()
            }
            numInt += if (isLike) 1 else -1
            entity.commentLikeCounts = numInt.toString()
            entity.isLike = if (isLike) "1" else "0"
            if (v.tag != null && v.tag is VideoComment) {
                var e1 = v.tag as VideoComment
                if (e1.commentCode == entity.commentCode) {
                    (v as TextView).text = entity.commentLikeCounts.toString()
                    v.isSelected = isLike
                }
            }
        }, {
        })
    }

    private fun clickOnChildPlaceholder(groupPosition: Int) {
        var groupItem = adapter?.getGroup(groupPosition)
        var state = groupItem?.let { adapter?.groupStateOf(it) }
        if (state?.clickToLoad!! && adapter?.isLoadingGroupId == null) {
            adapter?.isLoadingGroupId = groupItem?.comment?.commentCode
            adapter?.notifyDataSetChanged()
            groupItem?.let { loadChildComments(it) }
        }
        if (state == VideoCommentsAdapter.GroupState.AtEnd) {
            groupItem?.showChildren = false
            adapter?.notifyDataSetChanged()
        } else if (state == VideoCommentsAdapter.GroupState.AtBegin) {
            groupItem?.showChildren = true
            adapter?.notifyDataSetChanged()
        }
    }

     fun showReplyVideoDialog() {
        var dialog = context?.let { VideoCommentsInputDialog(it, "1") }
        dialog?.inputAction = { text ->
            video?.let {
                viewModel?.commentVideo(it, text, { commentId ->
                    var comment = createLocalComment(commentId, text)
                    var groupItem = VideoCommentsAdapter.GroupItem(comment)
                    adapter?.groups?.add(0, groupItem)
                    adapter?.notifyDataSetChanged()
                    for (i in 0 until adapter!!.groupCount) {
                        listView?.expandGroup(i)
                    }
                    listView?.setSelectedGroup(0);
                    if(adapter?.groups?.size==0){
                        initFooter("暂无评论", null)
                    }else{
                        initFooter("已显示全部评论", null)
                    }
                }, {
                    context?.errorToast(it)
                })
            }
        }
        dialog?.show()
        dialog?.editText?.hint = "评论"
    }

    private fun showReplyCommentDialog(
        group: VideoCommentsAdapter.GroupItem,
        comment: VideoComment?
    ) {
        var dialog = context?.let { VideoCommentsInputDialog(it, "1") }

        var videoCoverPath: String = video?.videoCoverPath.toString()
        dialog?.inputAction = { text ->
            viewModel?.commentComment(
                comment?.fromEmployeeCode.toString(),
                comment?.videoComment.toString(),
                group?.comment?.commentCode,
                comment?.commentCode,
                videoCoverPath,
                text,
                { commentId ->
                    var comment = createLocalComment(commentId, text).apply {
                        toEmployeeCode = comment?.fromEmployeeCode
                        toEmployeeName = comment?.fromEmployeeName
                        lvlNo = if (comment == null) "2" else "3"
                    }
                    var num: Int = 0
                    if (!Utils.isNull(group.comment.haveChild)) {
                        num = group.comment.haveChild.toInt()
                    }
                    num++
                    var numString: String = num.toString()
                    group.comment.haveChild = numString
                    group!!.children.add(0, comment)
                    group.showChildren = true
                    adapter?.notifyDataSetChanged()
                },
                {
                    context?.errorToast(it)
                })
        }
        dialog?.show()
        if (comment != null) {
            dialog?.editText?.hint = "回复 ${comment.fromEmployeeName}"
        } else {
            dialog?.editText?.hint = "回复 ${group.comment.fromEmployeeName}"
        }
    }

    private fun createLocalComment(commentId: String, content: String): VideoComment {
        var comment = VideoComment()
        comment.commentCode = commentId
        comment.fromEmployeeName =
            ShareUtils().getString(MyApp.appCtx, StaticClass.USER_NICKNAME, "")
        comment.fromEmployeeCode =
            ShareUtils().getString(MyApp.appCtx, StaticClass.EMPLOYEECODE, "")
        comment.videoComment = content
        comment.headPhotoThumbUrl =
            ShareUtils().getString(MyApp.appCtx, StaticClass.USER_AVATAR_URL, "")
        comment.createTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())
        comment.lvlNo = "1"
        comment.isLike = "0"
        comment.haveChild = "0"

        return comment
    }

    fun screenSizeInPixel(context: Context): Point {
        val dm = context.resources.displayMetrics
        val widthPixels = dm.widthPixels
        val heightPixels = dm.heightPixels
        return Point(Math.min(widthPixels, heightPixels), Math.max(widthPixels, heightPixels))
    }


    private fun loadMoreData() {
        if(isFirst){
            if (isLoading || isEnd) {
                return
            }
        }
        isFirst = true
        isLoading = true
        initFooter("加载中...", null)
        if(adapter==null){
            return
        }
        var pageNum = adapter!!.groupCount / pageSize
        getVideoComments(video!!.videoId, pageSize, pageNum, {
            if (pageNum == 0) {
                adapter?.isLoadingGroupId = null
                adapter?.groups?.clear()
            }
            adapter?.groups?.addAll(it.map { VideoCommentsAdapter.GroupItem(it) })

            adapter?.notifyDataSetChanged()
            for (i in 0 until adapter?.groupCount!!) {
                listView?.expandGroup(i)
            }
            isLoading = false
            if (it.size < pageSize) {
                isEnd = true
                if(adapter?.groups?.size==0){
                    initFooter("暂无评论", null)
                }else{
                    initFooter("已显示全部评论", null)
                }
            } else {
                initFooter("查看更多") { loadMoreData() }
            }
        }, {
            isLoading = false
            initFooter("加载出错,请点击重试") { loadMoreData() }
        })
    }

    private fun loadChildComments(group: VideoCommentsAdapter.GroupItem) {
        var pageSize = 10
        var pageNum = group.children.size / pageSize
        getVideoComments(group.comment.commentCode, pageSize, pageNum, {
            adapter?.isLoadingGroupId = null
            group.children.addAll(it)
            adapter?.notifyDataSetChanged()
        }, {
            adapter?.isLoadingGroupId = null
            adapter?.notifyDataSetChanged()
        })
    }

    private fun getVideoComments(
        code: String, pageSize: Int, pageNum: Int,
        _onSuccess: ((result: List<VideoComment>) -> Unit),
        _onError: ((error: String) -> Unit)
    ) {
        val params2: MutableMap<String, Any?> = HashMap()
        params2["code"] = code
        params2["pageNum"] = (pageNum + 1).toString()
        params2["pageSize"] = pageSize.toString()

        httpForm<VideoCommentsListResponse> {
            url = "api/video/selectCommentByCode"
            params = params2
            onSuccess = {
                _onSuccess.invoke(it.data ?: emptyList())
                var map: HashMap<String, String> = HashMap()
                map.put("totalCommentNum",it.total.toString())
                EventBus.getDefault().post(MyEvent(map))
            }
            onError = {
                _onError.invoke(it)
            }
        }
    }


    private fun initFooter(text: String, l: View.OnClickListener?) {
        footerView?.tv?.text = text
        if(text.equals("暂无评论")){
            footerView?.noData?.visibility = View.VISIBLE
        }else{
            footerView?.noData?.visibility = View.GONE
        }
        footerView?.setOnClickListener(l)
    }
}